package com.example.imtoken.modules.main.wallet.details.trade.record

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.entitys.http.TransactionsEntity
import com.example.imtoken.entitys.http.TransactionsEntityItem
import kotlinx.coroutines.launch

class TransactionRecordViewModel : BaseViewModel() {

    var type = 0
    var coin: String? = null

    var isLoadData = false

    private val _transactionsLiveData = MutableLiveData<Result<TransactionsEntity?>>()
    val transactionLiveData: LiveData<Result<TransactionsEntity?>>
        get() = _transactionsLiveData

    val transaction = ArrayList<TransactionsEntityItem>()

    private var page = 0

    fun getMoreTransactions() {
        viewModelScope.launch {
            val status = if (type == 3) 2 else 0
            val io = if (type == 3) 0 else type

            page++
            LogUtils.e(
                "viewModelScope",
                "type = $type",
                "coin = $coin",
                "page = $page",
                "status = $status",
                "io = $io"
            )

            _transactionsLiveData.value = try {
                val response =
                    RetrofitUtils.apiService?.transactions(coin ?: "eth", status, io, page)
                response?.run {
                    if (code == 0) {
                        if (data?.isNotEmpty() == true) {
                            Result.success(data)
                        } else {
                            Result.success(null)
                        }
                    } else {
                        Result.failure(Exception(msg))
                    }
                }
            } catch (e: Exception) {
                Result.failure(e)
            }

        }
    }

    fun getTransactions() {
        page = 0
        transaction.clear()

        getMoreTransactions()
    }
}